function proj_meta=get_proj_metaData(projID,load_eye,Acode)
% generates proj meta files based on analysis code in stacks.xlsx
% analysis code = 1: include in analysis
% generates a proj_meta data file on G:
%
% written by PZ & GK 2013-03-11

if nargin < 3
    Acode = [];
end

cn_str = 'PROVIDER=SQLOLEDB; Data Source=PIA1; initial catalog=ExpLog; User ID=explog_user; password=Keller123';
DB = adodb_connect(cn_str, 240);
sql = ['SELECT Stacks.stackid, Stacks.expid, Stacks.comment, Experiments.siteid, Experiments.analysiscode,',...
    'Sites.animalid, Sites.project, Sites.location, Animals.pi FROM Stacks INNER JOIN Experiments ON Stacks.expid=Experiments.expid ' ...
    'INNER JOIN Sites ON Experiments.siteid=Sites.siteid INNER JOIN Animals ON Sites.AnimalID=Animals.AnimalID ORDER BY Stacks.stackid'];
ExpLog = adodb_query(DB, sql);

adata_dir='\\argon.fmi.ch\keller.g\AData\';
% stacks_dir='\\argon.fmi.ch\keller.g\ExpLog\Stacks.xlsx';
meta_save_dir='\\argon.fmi.ch\keller.g\AData\_metaData\';

[channel_ps_id,channel_air_puff,channel_screen_photo_diode,channel_stim_id]=define_proj_channels(projID);

[~,host] = dos('hostname');
if ~isempty(regexp(host,'rig1-ana', 'once'))
    rd_dir = 'D:\RawData\';
elseif ~isempty(regexp(host,'rig2-ana', 'once'))
    rd_dir = 'D:\RawData\';
else
    rd_dir = '\\KELLER-RIG1-ANA\RawData\';
end

% [xls_num,xls_txt]=xlsread(stacks_dir);
% IDs column headers: siteIDs expIDs
% indices = strcmp(xls_txt(2:end,7),projID);
% indices = strcmp(ExpLog.project,projID);
if ~isempty(Acode)
    indices = strcmp(ExpLog.project,projID) & strcmp(ExpLog.analysiscode,Acode);
else
%     indices = sum([indices,strcmp(xls_txt(2:end,9),Acode)],2);
%     indices = find(indices==2);
indices = strcmp(ExpLog.project,projID);
end
all_proj_stackIDs = [cell2mat(ExpLog.siteid(indices)), cell2mat(ExpLog.expid(indices)), cell2mat(ExpLog.stackid(indices))];
[~,uniqueStacks]=unique(all_proj_stackIDs(:,2));
all_proj_expIDs = all_proj_stackIDs(uniqueStacks,1:2);
all_proj_siteIDs = unique(all_proj_expIDs(:,1));

animals={};
locations={};
for lnd=1:length(all_proj_siteIDs)
    animals{lnd} = cell2mat(ExpLog.animalid(find(cell2mat(ExpLog.stackid)==all_proj_siteIDs(lnd),1,'first')));
%     xls_txt{find(xls_num(:,3)==all_proj_siteIDs(lnd),1,'first')+1,4};
    locations{lnd} = cell2mat(ExpLog.location(find(cell2mat(ExpLog.stackid)==all_proj_siteIDs(lnd),1,'first')));
%     xls_txt{find(xls_num(:,3)==all_proj_siteIDs(lnd),1,'first')+1,8};
end

% animals = ExpLog.animalid(indices);
% locations = uniquecell(ExpLog.location(indices));
animalIDs = uniquecell(animals);
siteOrder=zeros(length(all_proj_siteIDs),1);
for hnd=1:length(animalIDs)
    cur_inds=ismember(animals,animalIDs(hnd));
    order=1:sum(cur_inds);
    siteOrder(cur_inds)=order;
end

proj_meta=struct;
cnt=1;
for knd=1:length(all_proj_siteIDs)
    cur_site=all_proj_siteIDs(knd);
    cur_exps=all_proj_expIDs(all_proj_expIDs(:,1)==cur_site,2);
%     use_exps=zeros(length(cur_exps),1);
%     for jnd=1:length(cur_exps)
%         if str2num(xls_txt{find(xls_num(:,2)==cur_exps(jnd),1,'first')+1,9})==str2num(Acode)
%             use_exps(jnd)=1;
%         end
%     end
%     cur_exps(~logical(use_exps))=[];
    if ~isempty(cur_exps)
        display(['************ Adding site ' num2str(all_proj_siteIDs(knd)) ' to meta file ************'])
        %load adata file for first exp to determine ini filename
        [adata_file,mouse_id,userID]=find_adata_file(cur_exps(1),adata_dir);
        orig=load([adata_dir userID '\' mouse_id '\' adata_file],'fnames');
        try
            nbr_piezo_layers=readini([rd_dir userID '\' mouse_id '\' orig.fnames{1}(1:end-3) 'ini'],'piezo.nbrlayers');
        catch
            nbr_piezo_layers=1;
            disp('ATTENTION - could not read nbr of piezo layers from ini file')
        end
        for bnd=1:length(cur_exps)
            [adata_file,mouse_id,userID]=find_adata_file(cur_exps(bnd),adata_dir);
            orig=load([adata_dir userID '\' mouse_id '\' adata_file],'ROIs','nbr_frames','aux_files','template','act_map','fnames');
            if iscell(orig.template)
                if size(orig.ROIs{1},2)==1
                    display('No ROIs selected - Aborting experiment')
                    continue
                else
                    for znd=1:nbr_piezo_layers
                        if ~isfield(orig.ROIs{znd}(1),'activity')
                            display('Activity has not been calculated - Aborting experiment')
                            continue
                        end
                    end
                end
            else
                if size(orig.ROIs,2)==1
                    display('No ROIs selected - Aborting experiment')
                    continue
                elseif ~isfield(orig.ROIs(1,1),'activity')
                    display('Activity has not been calculated - Aborting experiment')
                    continue
                end
            end
            aux_data=[];
            try
                for ind=1:length(orig.aux_files)
                    if exist([rd_dir userID '\' mouse_id '\' orig.aux_files{ind}],'file');
                        disp(['loading file ' orig.aux_files{ind} ' from the network RawData directory']);
                        curr_load_path=[rd_dir userID '\' mouse_id '\' orig.aux_files{ind}];
                    end
                    
                    tmp_data=load_lvd(curr_load_path);
                    tmp_frames=get_frame_times(tmp_data(2,:));
                    
                    if orig.nbr_frames(ind)~=length(tmp_frames)
                        if max(diff(tmp_frames))/median(diff(tmp_frames))<1.5 & length(tmp_frames)>orig.nbr_frames(ind)
                            disp('NC WARNING! Probably scanning too fast for FPGA to stop in the same frame')
                            disp(['--- ' num2str(length(tmp_frames)-orig.nbr_frames(ind)) ' frames too many ---'])
                            tmp_data(2,tmp_frames(orig.nbr_frames(ind)+1):end)=0;
                        else
                            disp('CRITICAL WARNING! - aux data longer than it should be.')
                            %return
                            %tmp_data=tmp_data(:,1:tmp_frames(nbr_frames(ind)+1));
                            [~,last_bad_frame]=max(diff(tmp_frames));
                            tmp_data=tmp_data(:,ceil(mean([tmp_frames(last_bad_frame) tmp_frames(last_bad_frame+1)])):end);
                        end
                    end
                    aux_data(:,end+1:end+length(tmp_data))=tmp_data;
                end
                frame_times=get_frame_times(aux_data(2,:));
            catch
                disp('Did not load aux data')
            end
            if load_eye
                idata=zeros(0,0,0,'uint8');
                imeta_data=[];
                no_eye_data=0;
                for ind=1:length(orig.aux_files)
                    if exist([rd_dir userID '\' mouse_id  '\' orig.aux_files{ind}(1:end-4) '.eye'],'file');
                        disp(['loading file ' orig.aux_files{ind}(1:end-4) '.eye' ' from the network RawData directory']);
                        curr_load_path=[rd_dir userID '\' mouse_id '\' orig.aux_files{ind}(1:end-4) '.eye'];
                    else
                        disp('No eye data found!')
                        no_eye_data=1;
                        break
                    end
                    [tmp_idata, tmp_imeta_data] = load_eye_monitor_data(curr_load_path,1);
                    orig.nbr_iframes(ind)=length(tmp_imeta_data);
                    if ind==1||sum(size(idata(:,:,1))==size(tmp_idata(:,:,1)))==2
                        idata(:,:,end+1:end+size(tmp_idata,3))=tmp_idata;
                    else
                        disp('Idata sizes don''t match - will improvise');
                        idata(1:size(tmp_idata,1),1:size(tmp_idata,2),end+1:end+size(tmp_idata,3))=tmp_idata;
                    end
                    
                    imeta_data(:,end+1:end+length(tmp_imeta_data))=tmp_imeta_data;
                end
                if ~no_eye_data
                    [iframe_times]=get_iframe_times(imeta_data,aux_data(1,:),orig.nbr_iframes);
                end
                try
                    [~, pupil_diam, pupil_pos, blink] = find_saccades(idata);
                    [pupil_diam,pupil_pos,blink]=map_eye_data_to_frame_times(pupil_diam,pupil_pos,blink,frame_times,iframe_times);
                catch
                    display('CRITICAL WARNING! eye analysis failed')
                end
            end
            [velP,velM,velP_ind,velM_ind,velP_raw,velM_raw]=get_vel_ind_from_adata(aux_data);
%             [velP,velM,velP_ind,velM_ind,velP_raw,velM_raw]=get_vel_ind_from_adata_M1(aux_data);
            velP_smoothed=smooth2(velP_raw,1000);
            velM_smoothed=smooth2(velM_raw,1000);
            
            ps_id=round(2*aux_data(channel_ps_id,:));
            air_puff=round(aux_data(channel_air_puff,:));
            stim_id=aux_data(channel_stim_id,:);
            
            try
                vis_speed=check_vis_speed(aux_data(channel_screen_photo_diode,:));
            catch
                vis_speed=zeros(1,length(aux_data));
            end
            
            for vnd=1:nbr_piezo_layers
                
                if bnd==1
                    proj_meta(cnt).nbr_piezo_layers=nbr_piezo_layers;
                    proj_meta(cnt).animal=mouse_id;
                    proj_meta(cnt).animalID=find(ismember(animalIDs,mouse_id));
                    proj_meta(cnt).siteID=siteOrder(knd);
                    proj_meta(cnt).cortical_layer=locations{knd};
                    proj_meta(cnt).ExpGroup=cur_exps';
                end
                
                if iscell(orig.template)
                    [act,ROIinfo]=get_smoothed_ROIs(orig.ROIs{vnd});
                    proj_meta(cnt).rd(vnd,bnd).template=orig.template{vnd};
                    proj_meta(cnt).rd(vnd,bnd).act_map=orig.act_map{vnd};
                    ft_index=vnd:nbr_piezo_layers:length(frame_times);
                else
                    [act,ROIinfo]=get_smoothed_ROIs(orig.ROIs);
                    proj_meta(cnt).rd(vnd,bnd).template=orig.template;
                    proj_meta(cnt).rd(vnd,bnd).act_map=orig.act_map;
                    ft_index=1:length(frame_times);
                end
                
                proj_meta(cnt).rd(vnd,bnd).act=act;
                proj_meta(cnt).rd(vnd,bnd).ROIinfo=ROIinfo;
                
                proj_meta(cnt).rd(vnd,bnd).timepoint=bnd;
                proj_meta(cnt).rd(vnd,bnd).piezo_layer=vnd;
                proj_meta(cnt).rd(vnd,bnd).fnames=orig.fnames;
                
                proj_meta(cnt).rd(vnd,bnd).ps_id=ps_id(frame_times(ft_index));
                proj_meta(cnt).rd(vnd,bnd).velM=velM(frame_times(ft_index));
                proj_meta(cnt).rd(vnd,bnd).velM_smoothed=velM_smoothed(frame_times(ft_index));
                proj_meta(cnt).rd(vnd,bnd).velP=velP(frame_times(ft_index));
                proj_meta(cnt).rd(vnd,bnd).velP_smoothed=velP_smoothed(frame_times(ft_index));
                proj_meta(cnt).rd(vnd,bnd).vis_speed=vis_speed(frame_times(ft_index));
                proj_meta(cnt).rd(vnd,bnd).stim_id=stim_id(frame_times(ft_index));
                proj_meta(cnt).rd(vnd,bnd).air_puff=air_puff(frame_times(ft_index));
                proj_meta(cnt).rd(vnd,bnd).nbr_frames=orig.nbr_frames/nbr_piezo_layers;
                
                if load_eye
                    proj_meta(cnt).rd(vnd,bnd).pupil_diam=pupil_diam(ft_index);
                    proj_meta(cnt).rd(vnd,bnd).pupil_pos=pupil_pos(:,ft_index);
                    proj_meta(cnt).rd(vnd,bnd).blink=blink(ft_index);
                end
            end
        end
        cnt=cnt+1;
    else
        display(['************ Site ' num2str(all_proj_siteIDs(knd)) ' not added to meta file - stacks reads 0 ************'])
    end
end
if isempty(Acode)
    save([meta_save_dir projID '_meta.mat'],'proj_meta','-v7.3');
else
    save([meta_save_dir projID '_' num2str(Acode) '_meta.mat'],'proj_meta','-v7.3');
end